﻿using Admin2024.Domain.Entity.System;
using Admin2024.Domain.IDomainService.System.IUserService;
using Admin2024.Domain.Interface;
using Admin2024.Domain.ObjValue;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Admin2024.Domain.DomainService.System.UserService
{
    public class UserProfileService : IUserProfileService
    {

        private readonly IRepository<AppUser> _UserRep = null!;

        private readonly IJwtService jwtService;

        public UserProfileService(IRepository<AppUser> userRep, IJwtService jwtService)
        {
            _UserRep = userRep;
            this.jwtService = jwtService;
        }

        public async Task<DomainResult<AppUser>> GetUserById(Guid Id)
        {
            var user = await _UserRep.GetByIdAsync(Id);
            if (user == null)
            {
                return DomainResult<AppUser>.Error("用户不存在");
            }
            if (user.IsDeleted == true)
            {
                return DomainResult<AppUser>.Error("用户已被删除");
            }
            return DomainResult<AppUser>.Success(user);
        }

        public async Task<DomainResult<AppUser>> GetUserInfo(string token)
        {
            JwtSecurityToken to = jwtService.ValidateToken(token);
            var userId = to.Claims.First(item => item.Type == "Id").Value;
        
            var user = await _UserRep.GetByIdAsync(Guid.Parse(userId));
            if (user == null)
            {

                return DomainResult<AppUser>.Error("用户不存在");
            }

            return DomainResult<AppUser>.Success(user);
        }



        //获取所有用户(分页)
        public async Task<DomainResult<List<AppUser>>> GetUsersWithPagination(int page, int pageSize)
        {
            var userList = await _UserRep.GetListAsync();
            
            if(userList.Count == 0)
            {
                return DomainResult<List<AppUser>>.Error("当前还没有任何用户");
            }
            var userListPage =  userList.Skip((page - 1) * pageSize).Take(pageSize).Where(item=> item.IsDeleted == false).ToList();

            return DomainResult<List<AppUser>>.Success(userListPage);
        }

        //修改用户信息
        public async Task<DomainResult<AppUser>> UpdateUserProfile(Guid Id,AppUser appUser)
        {
             var user = await _UserRep.GetByIdAsync(Id);
            if(user == null)
            {
                return DomainResult<AppUser>.Error("用户不存在");
            }
            user.Nickname = appUser.Nickname;
            user.Avatar = appUser.Avatar;
            user.Email = appUser.Email;
            user.QQ = appUser.QQ;
            user.Weixin = appUser.Weixin;
            user.Avatar = appUser.Avatar;
            user.Telephone = appUser.Telephone;

             await _UserRep.UpdateAsync(user);
            return DomainResult<AppUser>.Success(user);
        }
    }
}
